using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Modularity;
using Volo.Abp.Swashbuckle;
using Microsoft.OpenApi.Models;

namespace Matrix.ServiceDiscovery
{
    [DependsOn(
        typeof(MatrixServiceDiscoveryApplicationModule),
        typeof(AbpAspNetCoreMvcModule),
        typeof(AbpSwashbuckleModule)
    )]
    public class MatrixServiceDiscoveryHttpApiModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            ConfigureSwaggerServices(context);
            ConfigureMvcServices(context);
            ConfigureConventionalControllers(context);
        }

        private static void ConfigureConventionalControllers(ServiceConfigurationContext context)
        {
            context.Services.AddAbpConventionalControllers(options =>
            {
                // 配置Application Service自动转换为API Controller
                options.TypePredicate = type =>
                    typeof(IApplicationService).IsAssignableFrom(type) &&
                    !type.IsAbstract &&
                    type.IsClass;
            });
        }

        private static void ConfigureSwaggerServices(ServiceConfigurationContext context)
        {
            context.Services.AddAbpSwaggerGenWithOAuth(
                "Matrix.ServiceDiscovery",
                options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo
                    {
                        Title = "Matrix Service Discovery API",
                        Version = "v1",
                        Description = "Matrix Framework 服务发现模块 API 接口文档"
                    });

                    options.DocInclusionPredicate((docName, description) => true);
                    options.CustomSchemaIds(type => type.FullName);
                },
                tokenUrl: "/connect/token"
            );
        }

        private static void ConfigureMvcServices(ServiceConfigurationContext context)
        {
            var services = context.Services;

            // 配置 API 版本
            services.AddApiVersioning(options =>
            {
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0);
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

            // 配置 JSON 序列化
            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.WriteIndented = false;
                options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
            });
        }
    }
}